package com.zkx.system.interceptor;

import com.zkx.common.customAnnotation.preAuthorize;
import com.zkx.common.exception.APIException;
import com.zkx.system.generator.entity.UandRandA;
import com.zkx.common.result.ResultCode;
import com.zkx.common.utils.JWTUtils;
import com.zkx.common.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


//拦截器
@Component
public class JWTInterceptor implements HandlerInterceptor {
    @Autowired
    RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        UandRandA uandRandA;
        String accessName;
        preAuthorize p;
        //获取请求头中的令牌
        String token = request.getHeader("token");
        //token不存在
        if(token == null || token.equals("")){
            throw new APIException(ResultCode.TOKEN_EMPTY);
        }
        else{
            String answer = JWTUtils.getTokenInfo(token);
            if(answer.equals(token)&&redisUtil.hasKey(token)){
                HandlerMethod handlerMethod = (HandlerMethod) handler;
                //判断方法上是否有该注解
                boolean methodsAnnotationPresent = handlerMethod.getMethod().isAnnotationPresent(preAuthorize.class);
                //如果有该注解 获取该注解
                if(methodsAnnotationPresent){
                    p = handlerMethod.getMethodAnnotation(preAuthorize.class);
                    if(p!=null){
                        accessName = p.accessName();
                        uandRandA =  (UandRandA) redisUtil.get(token);
                        if(uandRandA.getAccesses()!=null){
                            if(uandRandA.getAccesses().contains(accessName)){
                                return true;
                            }
                            else{
                                throw new APIException(ResultCode.NO_PERMISSION);
                            }
                        }
                    }
                }
                else{
                    return true;
                }
            }
            else{
                throw new APIException(ResultCode.TOKEN_ERROR);
            }
        }
        return true;//放行请求
    }
}
